import React, { createContext, useState, ReactNode, useEffect } from 'react';
import { Menu } from '../components/layout/SideNav';
import {
  apiData,
  docsData,
  smartLinkData,
  apiData_zh,
  docsData_zh,
  smartLinkData_zh,
} from '../markdoc/menu';
import { useRouter } from 'next/router';

interface AppContextProps {
  isAPI: boolean;
  setIsAPI: (value: boolean) => void;
  items: Menu[];
  setItems: (items: Menu[]) => void;
  language: string;
  setLanguage: (lang: string) => void;
  showSideNav: boolean;
  setShowSideNav: (show: boolean) => void;
}

export const AppContext = createContext<AppContextProps | undefined>(undefined);

export const AppProvider = ({ children }: { children: ReactNode }) => {
  const [isAPI, setIsAPI] = useState(false);
  const [items, setItems] = useState<Menu[]>(docsData);
  const [language, setLanguage] = useState('en');
  const [showSideNav, setShowSideNav] = useState(true);
  const router = useRouter();

  useEffect(() => {
    if (
      router.pathname.includes('/payments') ||
      router.pathname.includes('/api') ||
      router.pathname.includes('/smart-link')
    ) {
      if (isAPI) {
        // API 文档菜单
        setItems(language === 'en' ? apiData : apiData_zh);
      } else if (router.pathname.includes('/smart-link')) {
        // 添加融合终端的判断
        // 融合终端菜单
        setItems(language === 'en' ? smartLinkData : smartLinkData_zh);
      } else {
        // 普通文档菜单
        setItems(language === 'en' ? docsData : docsData_zh);
      }
    } else {
      router.replace(`/`);
    }
  }, []);

  useEffect(() => {
    const updateItemsForLanguage = (lang: string) => {
      if (router.pathname !== '/') {
        setShowSideNav(true);
        // 获取当前路径
        const currentPath = router.pathname;
        // 移除末尾的语言代码并添加新的语言代码
        const newPath = currentPath.replace(/_(en|zh)$/, `_${lang}`);

        // 根据当前页面类型选择对应的菜单数据
        if (isAPI) {
          setItems(lang === 'en' ? apiData : apiData_zh);
        } else if (router.pathname.includes('/smart-link')) {
          setItems(lang === 'en' ? smartLinkData : smartLinkData_zh);
        } else {
          setItems(lang === 'en' ? docsData : docsData_zh);
        }

        // 使用新路径进行导航
        router.replace(newPath);
      }
    };

    updateItemsForLanguage(language);
  }, [language]); // 依赖 language，当 language 变化时执行

  return (
    <AppContext.Provider
      value={{
        isAPI,
        setIsAPI,
        items,
        setItems,
        language,
        setLanguage,
        showSideNav,
        setShowSideNav,
      }}
    >
      {children}
    </AppContext.Provider>
  );
};
